let express = require('express');
let router = express.Router();
require('./../util/util')
let User = require('../models/user');

// User.create(
//   {
//     userId: '001',
//     userName: "tom",
//     userPwd: '123456',
//     orderList: [],
//     cartList:[
//     {
//       productId: '',
//       productName: '',
//       salePrice: '',
//       productImage: '',
//       checked: '',
//       productNum: ''
//     }
//   ],
//   addressList: []
//   },
//   function(err){
//    if(!err){
//      console.log("插入成功111")
//    }
//   }
// )

// 用户登录
router.post('/login',function(req,res,next){
  let param = {
    userName: req.body.userName,
    userPwd: req.body.userPwd
  };
  User.findOne(param,function(err,doc){
    if(err){
      res.json({
        status: '0',
        msg:err.message
      })
    }else{
      if(doc){
       //将userId存入cookie
        res.cookie('userId',doc.userId,{
          path:'/',
          maxAge: 1000*60*60*24*20
        });
        //将userName存入cookie
        res.cookie('userName',doc.userName,{
          path:'/',
          maxAge: 1000*60*60*24*20
        });
        res.json({
          status:'0',
          msg:'',
          result:{
            userName:doc.userName,
          }
        })
      }
    }
  })
})
//用户注册
router.post('/register',function(req,res,next){

  let userName= req.body.userName
  let userPwd= req.body.userPwd
  let userId= Math.floor(Math.random()*10)+'62'+Math.floor(Math.random()*10+10)+'001';
  let param= {
      userId: userId,
      userName: userName,
      userPwd: userPwd,
      orderList: [],
      cartList:[],
      addressList: []
    
  }
User.create(
  param,
  function(err){
   if(err){
     res.json({
       status: '1',
       msg: err.message
     })
   }else{
     res.json({
       status:'0',
       msg:'',
       result:'用户注册成功'
     })
   }
  }
)
})

//后台用户删除
router.post('/deluser',function(req,res,next){
  let userId = req.body.userId
User.remove({'userId':userId},function(err,doc){
if(err){
  res.json({
    status:'1',
    msg:err.message,
    result:''
  })
}else{
  res.json({
    status:'0',
    msg:'',
    result:'删除成功'
  })
}
})
})

//退出接口
router.post('/logout',function(req,res,next){
  res.cookie('userId','',{
    path:'/',
    maxAge: -1
  });
  res.cookie('userName','',{
    path:'/',
    maxAge: -1
  });
  res.json({
    status: '0',
    msg:'',
    result:'退出成功'
  })
})

//检查登陆，防止刷新后，用户名消失
router.get('/checkLogin',function(req,res,next){
 if(req.cookies.userId){
  res.json({
    status: '0',
    msg:'',
    result: req.cookies.userName||''
  });
 }else{
   res.json({
     status:'1',
     msg:'用户未登录',
     result:''
   });
 }
})
//查询用户购物车
router.get('/cartList',function(req,res,next){
  let userId = req.cookies.userId;
  User.findOne({userId},function(err,doc){
    if(err){
      res.json({
        status:'1',
        msg:err.message
      })
    }else{
      if(doc){
        
        res.json({
          status:'0',
          msg:'',
          result:doc.cartList
        });
      }

    }
  })
})

//删除购物车中的商品
router.post('/cartDel',function(req,res,next){
  let userId= req.cookies.userId, productId= req.body.productId;
  User.update({userId},{$pull:{'cartList':{'productId' : productId}}},function(err,doc){
   if(err){
     res.json({
       status:'1',
       msg:err.message,
       result:''
     })
   }else{
     res.json({
       status:'0',
       msg:'',
       result:'succ'
     })
     
   }
  })
})
//修改购物车中的商品
router.post('/cartEdit',function(req,res,next){
 let userId= req.cookies.userId,
 productId= req.body.productId,
 productNum= req.body.productNum,
 checked= req.body.checked;
 User.update({'userId':userId,'cartList.productId':productId},{
   'cartList.$.productNum':productNum,
   'cartList.$.checked':checked
 },function(err,doc){
  if(err){
    res.json({
      status:'1',
      msg:err.message,
      result:''
    })
  }else{
    res.json({
      status:'0',
      msg:'',
      result:'succ'
    })
    
  }
 })
})

//购物车中商品全选
router.post('/editCheckAll',function(req,res,next){
let userId = req.cookies.userId,
checkAll= req.body.checkAll;
User.findOne({'userId':userId},function(err,doc){
if(err){
  res.json({
    status:'1',
    msg:err.message,
    result:''
  })
}else{
  if(doc){
    doc.cartList.forEach(item => {
      item.checked= checkAll ? 1 : 0 ;
    });
  }
  //更改完数据要保存到数据库中
  doc.save(function(err1,doc1){
    if(err1){
      res.json({
        status:'1',
        msg:err.message,
        result:''
      })
    }else{
      res.json({
        status:'0',
        msg:'',
        result:'succ'
      })
    }
  })
}
})
})

//用户地址查询
router.get('/addressList',function(req,res,next){
let userId = req.cookies.userId;
User.findOne({'userId':userId},function(err,doc){
if(err){
  res.json({
    status:'1',
    msg:err.message,
    result:''
  })
}else{
  res.json({
    status:'0',
    msg:'',
    result:doc.addressList
  })
}
})
})

//用户地址删除
router.post('/delAddress',function(req,res,next){
let userId= req.cookies.userId, addressId= req.body.addressId;
  User.update({'userId':userId},
  {
    $pull:{
      addressList:{  'addressId':addressId   }
    }
  },function(err,doc){
    if(err){
      res.json({
        status:'1',
        msg:err.message,
        result:''
      })
    }else{
      res.json({
        status:'0',
        msg:'',
        result:'delete succ'
      })
    }
  })
})

//设置默认地址
router.post('/setDefault',function(req,res,next){
  let userId = req.cookies.userId,addressId= req.body.addressId;
  
  User.findOne({'userId':userId},function(err,doc){
    if(err){
      res.json({
        status:'1',
        msg:err.message,
        result:''
      })
    }else{
      
        doc.addressList.forEach((item)=>{
         if(item.addressId==addressId){
           item.isDefault= true;
         }else{
          item.isDefault= false;
         }
        })
       doc.save(function(err1,doc1){
        if(err1){
          res.json({
            status:'1',
            msg:err1.message,
            result:''
          })
        }else{
          res.json({
            status:'0',
            msg:'',
            result:'succ'
          })
        
        }
       })
    }
  })
 
})

//提交订单信息接口
router.post("/payMent",function(req,res,next){
let userId= req.cookies.userId,
    addressId= req.body.addressId,
    orderTotal= req.body.orderTotal;
    User.findOne({userId:userId},function(err,doc){
      if(err){
        res.json({
          status:'1',
          msg:err.message,
          result:''
        })
      }else{
        var address= '',goodsList= [];
        //获取当前用户的地址信息
        doc.addressList.forEach((item)=>{
          if(item.addressId==addressId){
            address = item;
          }
        })
        //获取用户购物车信息
        doc.cartList.forEach((item)=>{
          if(item.checked=='1'){
             goodsList.push(item);
          }
        });
        let platform = '622';
        let r1 = Math.floor(Math.random()*10);
        let r2 = Math.floor(Math.random()*10);
        let sysDate = new Date().Format('yyyyMMddhhmmss');
        let createDate= new Date().Format('yyyy-MM-dd hh:mm:ss');
        let orderId= platform+r1+sysDate+r2;
        let order = {
          orderId:orderId,
          orderTotal:orderTotal,
          adderssInfo:address,
          goodsList:goodsList,
          orderStatus:'1',
          createDate:createDate
        };
        doc.orderList.push(order);
        doc.save(function(err1,doc1){
          if(err1){
            res.json({
              status:'1',
              msg:err.message,
              result:''
            })
          }else{
            res.json({
              status:'0',
              msg:'',
              result:{
                orderId:order.orderId,
                orderTotal:order.orderTotal
              }
            });
          }
        })
        
        
      }
    })
})

//根据orderId查询用户订单
router.get("/orderDetail", function (req,res,next) {
  var userId = req.cookies.userId,orderId = req.param("orderId");
  User.findOne({userId:userId}, function (err,userInfo) {
      if(err){
          res.json({
             status:'1',
             msg:err.message,
             result:''
          });
      }else{
         var orderList = userInfo.orderList;
         if(orderList.length>0){
           var orderTotal = 0;
           orderList.forEach((item)=>{
              if(item.orderId == orderId){
                orderTotal = item.orderTotal;
              }
           });
           if(orderTotal>0){
             res.json({
               status:'0',
               msg:'',
               result:{
                 orderId:orderId,
                 orderTotal:orderTotal
               }
             })
           }else{
             res.json({
               status:'120002',
               msg:'无此订单',
               result:''
             });
           }
         }else{
           res.json({
             status:'120001',
             msg:'当前用户未创建订单',
             result:''
           });
         }
      }
  })
});

//获取用户列表
router.get("/name",function(req,res,next){
  User.find({},function(err,doc){
    if(!err){
      var userList= [];
      doc.forEach( item =>{
       userList.push(item.userName)
       
    })
    if(userList){
      res.json({
        status:'0',
        msg:'',
        result: userList
      })
    }else{
      res.json({
        status:'1',
        msg: err.message,
        result:''
      })
    }
    }
    })
})
// 用户地址添加
router.post('/addAddress',function(req,res,next){
  let userId = req.cookies.userId;
  let addressId = "63"+ Math.floor( Math.random()*10) + Math.floor(Math.random()*10+10) + Math.floor(Math.random()*10+100)+"001"
  let param={
    addressId: addressId ,
    userName: req.body.name,
    streetName: req.body.address,
    postCode: req.body.pcode,
    tel: req.body.tel,
    isDefault: false
  }
  User.findOne({userId},function(err,doc){
   
    
    if(!err){
   
      doc.addressList.push(param);
  
      
      doc.save(function(err2,doc2){
        if(err2){
          res.json({
            status:'1',
            msg:err.message,
            result:''
          })
        }else{
          res.json({
            status:'0',
            msg:'',
            result:'succ'
          })
        }
      })
    }
  })
})
router.get('/',function(req,res,next){
  User.find({},function(err,doc){
   if(err){
     res.json({
       status:'1',
       msg:err.message,
       result:''
     })
   }else{
     res.json({
      status:'0',
      msg:'',
      result:doc
     })
   }
  })
})

module.exports = router;